<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="albumQuery.name" placeholder="关键词" />
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="getList()"
        >查询</el-button
      >
      <el-switch
        v-model="albumQuery.sortValue"
        active-text="最热"
        active-value="score"
        inactive-text="最新"
        inactive-value="create_time"
        @change="handleSwitchChange"
      >
      </el-switch>

      <el-button type="default" @click="resetData()">清空</el-button>
      <el-button
        type="success"
        @click="addAlbum"
        v-show="ROLE === 'admin' || ROLE === 'band'"
        >发布专辑</el-button
      >
    </el-form>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="followed" label="关注" width="100" align="center">
        <template slot-scope="scope">
          <el-button
            :type="scope.row.followed ? 'success' : 'warning'"
            size="mini"
            @click="followAlbum(scope.row.id)"
          >
            {{ scope.row.followed ? "已关注" : "+关注" }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="专辑名" width="80" />

      <el-table-column prop="description" label="专辑描述" />
      <el-table-column prop="bandName" label="乐队" width="110" />

      <el-table-column prop="createTime" label="发布时间" width="160">
        <template slot-scope="scope">
          {{ new Date(scope.row.createTime).toLocaleDateString() }}
        </template>
      </el-table-column>
      <el-table-column prop="score" label="评分" width="180"> </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="showScoring(scope.row.id)"
            style="font-size: 12px"
            >评分</el-button
          >
          <el-button
            type="text"
            @click="selectSongs(scope.row.id)"
            style="font-size: 12px"
            >歌曲</el-button
          >
          <el-button
            type="text"
            @click="commentForm(scope.row.id)"
            style="font-size: 12px"
            >评论</el-button
          >
          <el-button
            type="text"
            @click="edit(scope.row.id)"
            style="font-size: 12px"
            v-show="ROLE === 'admin' || ROLE === 'band'"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="removeDataById(scope.row.id)"
            style="font-size: 12px"
            v-show="ROLE === 'admin' || ROLE === 'band'"
            >删除</el-button
          >
        </template></el-table-column
      ></el-table
    >
    <!-- 个人信息窗口 -->
    <el-dialog title="个人信息" :visible.sync="userInfoVisible">
      <el-form :model="userInfo">
        <el-form-item label="头像" label-width="120px">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-form-item>

        <el-form-item label="用户名" label-width="120px">
          <el-input :disabled="true" v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="120px">
          <el-input :disabled="true" v-model="userInfo.gender">{{
            userInfo.gender === 0 ? "女" : "男"
          }}</el-input>
        </el-form-item>
        <el-form-item label="年龄" label-width="120px">
          <el-input :disabled="true" v-model="userInfo.age"></el-input>
        </el-form-item>
        <el-form-item label="学历" label-width="120px">
          <el-input :disabled="true" v-model="userInfo.education"></el-input>
        </el-form-item>
        <el-form-item label="职业" label-width="120px">
          <el-input :disabled="true" v-model="userInfo.profession"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px">
          <el-input :disabled="true" v-model="userInfo.email"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 评论对话框 -->
    <el-dialog title="评论" :visible.sync="commentVisible" width="1000px">
      <el-switch
        v-model="commentOrder"
        active-text="最早"
        active-value="asc"
        inactive-text="最新"
        inactive-value="desc"
        @change="handleOrderChange"
      >
      </el-switch>
      <template>
        <div class="comment-list">
          <div
            v-for="comment in comments"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-info">
              <!-- 用户头像 -->
              <img
                :src="comment.avatar"
                alt="用户头像"
                class="user-avatar"
                @click="shouUserInfo(comment.username)"
              />
              <div class="user-info">
                <p class="username">{{ comment.username }}</p>
                <p class="comment-time">{{ formatTime(comment.createTime) }}</p>
              </div>
            </div>
            <div class="comment-content">
              <p>{{ comment.content }}</p>
            </div>
          </div>
        </div>
      </template>

      <template v-slot:footer>
        <div class="comment-input">
          <el-input
            v-model="comment.description"
            placeholder="请输入评论内容，不超过200字"
            type="textarea"
            :rows="3"
          ></el-input>
          <el-button @click="saveComment" type="primary">发表评论</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评分窗口 -->
    <el-dialog title="评分" :visible.sync="scoringVisible" width="30%">
      <el-input-number
        v-model="score.score"
        @change="handleChange"
        :min="1"
        :max="10"
        label="评分"
        :disabled="scoreDisable"
      ></el-input-number>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scoringVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitScore" :disabled="scoreDisable"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 歌曲窗口 -->
    <el-dialog title="歌曲信息" :visible.sync="songEditVisible">
      <el-form label-width="80px" :model="song">
        <el-form-item label="歌名">
          <el-input v-model="song.name"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="song.author"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="songEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateSong">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 歌曲列表窗口 -->
    <el-dialog
      title="歌曲"
      :visible.sync="songsFormVisible"
      width="60%"
      height="80%"
    >
      <el-button
        type="success"
        @click="addSong"
        plain
        v-show="ROLE === 'admin' || ROLE === 'band'"
        >添加歌曲</el-button
      >
      <el-table :data="songs">
        <!-- 表格的其他表单项代码 -->
        <el-table-column
          prop="followed"
          label="关注"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              :type="scope.row.followed ? 'success' : 'warning'"
              size="mini"
              @click="followSong(scope.row.id)"
            >
              {{ scope.row.followed ? "已关注" : "+关注" }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column property="name" label="歌名"> </el-table-column>
        <el-table-column property="author" label="作者"> </el-table-column>
        <el-table-column
          label="操作"
          width="160"
          v-if="ROLE === 'admin' || ROLE === 'band'"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="editSong(scope.row.id)"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              type="danger"
              @click="deleteSong(scope.row.id)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="songsFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="songsFormVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑窗口 -->
    <el-dialog title="编辑专辑" :visible.sync="editFormVisible">
      <el-form label-width="80px" :model="album">
        <el-form-item label="名称">
          <el-input v-model="album.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="album.description"></el-input>
        </el-form-item>
        <el-form-item label="评分">
          <el-input v-model="album.score" disabled></el-input>
        </el-form-item>
        <el-form-item label="乐队">
          <el-select v-model="album.bandId">
            <el-option
              v-for="item in bands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="album.createTime"
            type="date"
            format="yyyy-MM-dd"
            disabled
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAlbum">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 添加窗口 -->
    <el-dialog title="发布专辑" :visible.sync="addFormVisible">
      <el-form label-width="80px" :model="album">
        <el-form-item label="名称">
          <el-input v-model="album.name"></el-input>
        </el-form-item>
        <el-form-item label="专辑描述">
          <el-input v-model="album.description"></el-input>
        </el-form-item>
        <el-form-item label="乐队">
          <el-select v-model="album.bandId">
            <el-option
              v-for="item in bands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAlbum">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />
  </div>
</template>
    <script>
//引入js文件
import {
  getAlbumListPage,
  deleteAlbum,
  addAlbum,
  getAlbum,
  updateAlbum,
  scoring,
  getScore,
} from "@/api/album";
import { selectAll } from "@/api/band";
import {
  selectByAlbumId,
  addSong,
  deleteSong,
  getSongById,
  updateSong,
} from "@/api/song";
import { getToken } from "@/utils/auth";
import { getComments, addComment } from "@/api/comment";
import { getByUsername } from "@/api/user";
import { follow } from "@/api/follow";
import { getInfo } from "@/api/user";
export default {
  // data:{}
  data() {
    return {
      ROLE: "",
      //评论相关
      userInfoVisible: false,
      userInfo: {}, //用户信息
      commentOrder: "desc", //排序方式
      comment: {
        fanId: 0,
        albumId: 0,
        description: "",
      },
      comments: [],

      commentVisible: false, //评论窗口是否可见
      scoreDisable: false, //是否可以点击评分
      score: {
        //评分对象
        fanId: 0,
        albumId: 0,
        score: 0,
      },
      scoringVisible: false, //评分窗口是否可见
      albumId: 0,
      songEditVisible: false, //歌曲信息窗口
      song: {},
      songs: [], //歌曲列表
      songsFormVisible: false, //歌曲列表窗口
      editFormVisible: false, //编辑窗口
      bands: {}, //乐队信息
      album: {}, //专辑实体
      addFormVisible: false, //添加窗口
      albumQuery: {
        name: "",
        sortValue: "create_time", //默认时间降序
      },

      listLoading: true, //是否显示“数据加载中这几个字”

      list: [], //封装返回的数据
      total: 0, //数据条数
      currentPage: 1, //当前页码
      pageSize: 5, //每页显示条数
    };
  },
  created() {
    this.setUserRole();
    this.getList();
  },
  methods: {
    //设置用户角色
    setUserRole() {
      let userId = getToken();
      getInfo(userId).then((res) => {
        this.ROLE = res.data.roles[0];
      });
    },
    //关注、取关歌曲
    followSong(id) {
      let userId = getToken();
      let type = 2; //2代表歌曲
      let entityId = id;
      follow(userId, type, entityId).then((res) => {
        this.$message.success("成功");
        this.selectSongs(this.albumId);
      });
    },
    //关注、取关专辑
    followAlbum(id) {
      let userId = getToken();
      let type = 1; //1代表专辑
      let entityId = id;
      follow(userId, type, entityId).then((res) => {
        this.$message.success("成功");
        this.getList();
      });
    },
    //评论相关
    //点击头像查看用户信息
    shouUserInfo(username) {
      this.userInfoVisible = true;
      getByUsername(username).then((res) => {
        this.userInfo = res.data.row;
      });
    },
    //评论排序
    handleOrderChange() {
      this.getCommentData();
    },
    //评论的时间格式
    formatTime(dateTime) {
      return new Date(dateTime).toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
      });
    },
    //获取评论
    getCommentData() {
      //设置
      getComments(this.albumId, this.commentOrder).then((res) => {
        this.comments = res.data.rows;
      });
    },
    //保存评论
    saveComment(comment) {
      //封装对象
      this.comment.albumId = this.albumId;
      this.comment.fanId = getToken();
      addComment(this.comment).then((res) => {
        this.$message.success("评论成功");
        //清空评论框
        this.comment.description = "";
        //重新获取评论
        this.getCommentData();
      });
    },
    //显示评论
    commentForm(id) {
      this.albumId = id;
      this.commentVisible = true;

      this.getCommentData();
    },

    //打分
    submitScore() {
      scoring(this.score)
        .then((res) => {
          this.$message.success("打分成功");
          this.scoringVisible = false;
          //刷新页面
          this.getList();
        })
        .catch((err) => {
          this.$message.error(err.data);
        });
    },
    //评分窗口
    showScoring(id) {
      //获取用户id
      let userId = getToken();
      this.score.fanId = userId;
      this.score.albumId = id; //设置专辑id
      //查询该用户是否评过分，初始化为他评的分 | 1
      getScore(this.score.fanId, this.score.albumId).then((res) => {
        if (res.data.row != null) {
          //已经评过分，设置初始分，并禁用评分按钮
          this.score.score = res.data.row.score;
          this.scoreDisable = true;
          this.$message.info("您已评分");
        } else {
          this.score.score = 1;
          this.scoreDisable = false;
        }
      });

      this.scoringVisible = true;
    },
    //删除歌曲
    deleteSong(id) {
      this.$confirm("此操作将永久删除该歌曲, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用删除方法
          deleteSong(id).then((res) => {
            this.$message.success("删除成功");
            this.songsFormVisible = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //新增或修改
    updateSong() {
      // console.log(this.song.id);
      if (this.song.id === undefined) {
        // console.log(this.song);
        //新增
        addSong(this.song).then((res) => {
          this.$message.success("添加成功");
        });
      } else {
        //修改
        updateSong(this.song).then((res) => {
          this.$message.success("修改成功");
        });
      }
      this.songEditVisible = false;
      this.songsFormVisible = false;
    },
    //编辑歌曲
    editSong(id) {
      this.songEditVisible = true;
      //回显
      getSongById(id).then((res) => {
        this.song = res.data.row;
      });
    },
    //添加歌曲
    addSong() {
      //清空对话框
      this.song = {};
      //!!设置专辑id
      this.song.albumId = this.albumId;
      // console.log(this.song);
      //打开对话框
      this.songEditVisible = true;
    },
    //查找该专辑的歌曲
    selectSongs(id) {
      let userId = getToken();
      selectByAlbumId(userId, id).then((res) => {
        //打开对话框
        this.songsFormVisible = true;
        this.songs = res.data.rows;
        // console.log(this.songs)
        //设置这些歌曲属于那个专辑
        this.albumId = id;
      });
    },
    //更新专辑信息
    updateAlbum() {
      updateAlbum(this.album).then((res) => {
        this.$message.success("更新成功");
        this.editFormVisible = false;
        this.getList();
      });
    },
    //编辑对话框
    edit(id) {
      //打开对话框
      this.editFormVisible = true;
      //查询有哪些乐队
      selectAll().then((res) => {
        this.bands = res.data.rows;
      });
      //查询专辑，用于回显
      getAlbum(id).then((res) => {
        this.album = res.data.row;
      });
    },
    //保存
    saveAlbum() {
      // console.log(this.album);
      addAlbum(this.album).then((res) => {
        this.$message.success("发布成功");
        //关闭对话框
        this.addFormVisible = false;
        //刷新页面
        this.getList();
      });
    },
    //打开对话框及数据初始化
    addAlbum() {
      //清空原对话框
      this.album = {};
      //查询有哪些乐队
      selectAll().then((res) => {
        this.bands = res.data.rows;
      });
      //打开添加对话框
      this.addFormVisible = true;
    },
    //开关发生变化时
    handleSwitchChange() {
      this.getList();
    },
    //分页查询
    getList(currentPage = 1) {
      //默认第一页
      this.currentPage = currentPage;
      let userId = getToken();
      getAlbumListPage(userId, this.currentPage, this.pageSize, this.albumQuery)
        .then((res) => {
          // console.log(res.data.rows);
          this.total = res.data.total;
          this.list = res.data.rows;
          // console.log(this.total)
          // console.log(this.list)
          this.listLoading = false; //将“数据加载中”这几个字关掉
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleChange(value) {
      // console.log(value);
    },
    resetData() {
      //清空查询条件
      this.albumQuery.name = "";
      this.getList();
    },
    removeDataById(id) {
      // console.log("专辑id:", id);
      //删除方法
      //提示信息
      this.$confirm("此操作将永久删除该专辑, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用删除方法
          deleteAlbum(id).then((res) => {
            this.$message.success("删除成功");
            this.getList(); //刷新页面
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style scoped>
.comment-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #06f676;
  border-radius: 5px;
}

.comment-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
  margin: 0;
}

.comment-time {
  color: gray;
  margin: 0;
}

.comment-content {
  /* 留空 */
}
</style>

  <style>
.form-container {
  display: flex;
  justify-content: flex-end;
}
</style>